package com.yyb.interceptor;

import com.alibaba.fastjson2.JSON;
import com.yyb.common.Result;
import com.yyb.constants.CoreConstant;
import com.yyb.enums.ResultEnums;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

/**
 * 
 * 
 * 
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断session里面有没有用户数据
        Object user = request.getSession().getAttribute(CoreConstant.SESSION_KEY);
        if(!ObjectUtils.isEmpty(user)){
            //放行
            return true;
        }
        //写一个未登录的JSON出去
        Result result=new Result(ResultEnums.USER_NOT_LOGIN);
        //转成JSON
        String json = JSON.toJSONString(result);
        //设置响应编码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json;charset=utf-8");
        //写出去
        PrintWriter writer = response.getWriter();
        writer.write(json);
        writer.flush();
        writer.close();
        return false;
    }
}
